/**
 * 生成路由
 */
import navConfig from '@/nav.config.json'
import { RouteConfig } from 'vue-router'

export interface INav {
  name: string
  dirPath: string
  children?: Array<{ name: string; path: string; }>
  groups?: Array<{ groupName: string; list: Array<{ path: string; title: string; }>; }>
}

function loadComponent(path, name) {
  return () => import(/* webpackChunkName: "vender_com"*/`@/views/${path}${name}/index.vue`)
}

function handlePath(path: string) {
  return path.substr(1, path.length)
}

function genRoute(navList: INav[]) {
  const route: RouteConfig[] = []
  navList.forEach(item => {
    const children = item.children || []
    const groups = item.groups || []
    children.forEach(t => {
      const com = loadComponent(item.dirPath, t.path)
      route.push({
        path: handlePath(t.path),
        component: com,
      })
    })
    for (let i = 0; i < groups.length; i++) {
      const list = groups[i].list || []
      list.forEach(t => {
        const com = loadComponent(item.dirPath, t.path)
        route.push({
          path: handlePath(t.path),
          component: com,
        })
      })
    }
  })
  return route
}
const router = genRoute(navConfig)

export default router
